package com.wudimeng.syll.utils;

import java.security.MessageDigest;

public class Security extends _this {
    
    //密码加密
	public static String getPassWordStr(String str) {
		String pw = getMD5Str(str);
		return getSHA256Str(pw);
	}
	
	//SHA256加密
	public static String getSHA256Str(String str) {
		return getPwdStr(str, "SHA-256");
	}

	
	//MD5加密
	public static String getMD5Str(String str) {
		return getPwdStr(str, "MD5");
	}
	
	//利用java原生的加密算法
	private static String getPwdStr(String str, String type) {
		MessageDigest messageDigest;
		String encodeStr = "";
		try {
			messageDigest = MessageDigest.getInstance(type);
			messageDigest.update(str.getBytes("UTF-8"));
			encodeStr = parseByte2HexStr(messageDigest.digest()); //将密文转换成16进制
			return stringBlank(encodeStr);
		} catch (Exception e) {
			System.out.println(e);
			return null;
		}
	}

	//将byte转为16进制
	private static String parseByte2HexStr(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		String temp = null;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
				// 1得到一位的进行补0操作
				stringBuffer.append("0");
			}
			stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}
	
	//将16进制转换为二进制
	@SuppressWarnings("unused")
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

    //stringBlank格式转化null""化为""
    private static String stringBlank(String value) {
        if (value == null || value.equals("")) {
            value = "";
        }
        return value.replaceAll("\r|\n", "");
    }
}
